﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Jy123.DBUtility;

namespace Jy123.BLL.TCenter
{
    public class TModule : Jy123.BLL.Public.Module<Jy123.Model.TCenter_Main>
    {
        /// <summary>
        /// 组件升级(条件)
        /// </summary>
        /// <param name="id">组件ID</param>
        /// <param name="ckey">条件组</param>
        /// <param name="cvalue">条件值组</param>
        /// <param name="money">升级所需金钱</param>
        /// <returns>成功失败</returns>
        public override bool LevelUpByCondition(int id, List<string> cKey, List<int> cValue, decimal money)
        {
            Jy123.BLL.TCenter_Main BLLTCenterMain = new Jy123.BLL.TCenter_Main();
            Jy123.Model.TCenter_Main TCenter = BLLTCenterMain.GetModel(id);
            Jy123.BLL.User_Main BLLUserMain = new Jy123.BLL.User_Main();
            Jy123.Model.User_Main user = BLLUserMain.GetModel(TCenter.FUser.Value);
            if (user.Cash >= money)
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("SELECT ");
                int count = cKey.Count;
                for (int i = 0; i < count - 1; i++)
                {
                    strSql.Append(cKey[i].ToString());
                    strSql.Append(",");
                }
                strSql.Append(cKey[count - 1]);
                strSql.AppendFormat(" FROM TCenter_Main WHERE ID = {0}", id);
                DataSet dsResult = DbHelperSQL.Query(strSql.ToString());//获取组件对应字段的值
                if (dsResult != null)
                {
                    DataRow drResult = dsResult.Tables[0].Rows[0];
                    for (int j = 0; j < cValue.Count; j++)
                    {
                        string keyName = cKey[j].ToString();
                        int iResult = int.Parse(drResult[keyName].ToString());
                        int iValue = int.Parse(cValue[j].ToString());
                        if (iResult < iValue)
                        {
                            return false;//比较组件对应各字段是否达到升级条件
                        }
                    }
                }
                else
                {
                    return false;
                }
                return true;
            }
            return false;
        }

        /// <summary>
        /// 返回好友俱乐部组件列表
        /// </summary>
        /// <param name="userId">用户ID</param>        
        /// <returns>该类型俱乐部对象组</returns>
        public List<Jy123.Model.Club_Main> FriendsClub(int userId, bool status)
        {
            Club_Main BLLClubMain = new Club_Main();
            StringBuilder strWhere = new StringBuilder();
            strWhere.Append("FUser IN (");
            strWhere.Append("SELECT FFriend FROM User_Friend ");
            strWhere.AppendFormat("WHERE FUser = {0}) ", userId);
            if (status)
            {
                strWhere.Append("AND ID IN (");
                strWhere.AppendFormat("SELECT ID FROM Module_Main WHERE MStatus = 0 OR  MStatus = 2)");//表示组件为空闲或者比赛
            }
            List<Jy123.Model.Club_Main> resultList = BLLClubMain.GetModelList(strWhere.ToString());
            return resultList;
        }

        /// <summary>
        /// 返回好友训练中心列表
        /// </summary>
        /// <param name="id">组件ID</param>
        /// <returns>该类型组件对象组</returns>
        public override List<Jy123.Model.TCenter_Main> FriendsModule(int id)
        {
            Jy123.BLL.TCenter_Main BLLTCenterMain = new Jy123.BLL.TCenter_Main();
            Jy123.Model.TCenter_Main TCenter = BLLTCenterMain.GetModel(id);
            int userId = TCenter.FUser.Value;
            StringBuilder strWhere = new StringBuilder();
            strWhere.Append("FUser IN (");
            strWhere.Append("SELECT FFriend FROM User_Friend ");
            strWhere.AppendFormat("WHERE FUser = {0})", userId);
            List<Jy123.Model.TCenter_Main> resultList = BLLTCenterMain.GetModelList(strWhere.ToString());
            return resultList;
        }
        /// <summary>
        /// 返回组件列表
        /// </summary>
        /// <param name="field">列名</param>
        /// <param name="count">总数</param>
        /// <param name="order">排序类型([T]asc[F]Desc)</param>
        /// <returns>该类型组件对象组</returns>
        public override List<Jy123.Model.TCenter_Main> OrderModule(string field, int count, bool order)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.AppendFormat("SELECT TOP {0} * FROM TCenter_Main ", count);
            string strOrder = "ASC";
            if (!order)
            {
                strOrder = "DESC";
            }
            strSql.AppendFormat("ORDER BY {0} {1}", field, strOrder);
            DataSet ds = DbHelperSQL.Query(strSql.ToString());//获取DataSet
            List<Jy123.Model.TCenter_Main> modelList = DataSetToModelList(ds);
            return modelList;
        }
        /// <summary>
        /// 返回好友组件列表
        /// </summary>
        /// <param name="id">组件ID</param>
        /// <param name="field">列名</param>
        /// <param name="count">总数</param>
        /// <param name="order">排序类型([T]asc[F]Desc)</param>
        /// <returns>该类型组件对象组</returns>
        public override List<Jy123.Model.TCenter_Main> OrderMFriend(int id, string field, int count, bool order)
        {
            Jy123.BLL.TCenter_Main BLLTCenterMain = new Jy123.BLL.TCenter_Main();
            Jy123.Model.TCenter_Main TCenter = BLLTCenterMain.GetModel(id);
            int userId = TCenter.FUser.Value;
            StringBuilder strSql = new StringBuilder();
            strSql.AppendFormat("SELECT TOP {0} * FROM TCenter_Main ", count);
            strSql.Append("WHERE FUser IN (");
            strSql.Append("SELECT FFriend FROM User_Friend ");
            strSql.AppendFormat("WHERE FUser = {0})", userId);
            string strOrder = "ASC";
            if (!order)
            {
                strOrder = "DESC";
            }
            strSql.AppendFormat(" ORDER BY {0} {1}", field, strOrder);
            DataSet ds = DbHelperSQL.Query(strSql.ToString());//获取DataSet

            List<Jy123.Model.TCenter_Main> modelList = DataSetToModelList(ds);
            return modelList;
        }

        /// <summary>
        /// 返回好友某个类型赛场组件列表
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="JType">赛场类型</param>
        /// <returns>该类型赛场对象组</returns>
        public List<Jy123.Model.TCenter_Main> FriendsTCenter(int userId, bool status)
        {
            TCenter_Main BLLTCenterMain = new TCenter_Main();
            StringBuilder strWhere = new StringBuilder();
            strWhere.Append("FUser IN (");
            strWhere.Append("SELECT FFriend FROM User_Friend ");
            strWhere.AppendFormat("WHERE FUser = {0}) ", userId);
            if (status)
            {
                strWhere.Append("AND ID IN (");
                strWhere.AppendFormat("SELECT ID FROM Module_Main WHERE (MStatus = 0 OR MStatus = 1))");//表示组件为空闲或者非满员训练状态
            }
            strWhere.Append(" ORDER BY TStatus ASC");
            List<Jy123.Model.TCenter_Main> resultList = BLLTCenterMain.GetModelList(strWhere.ToString());
            return resultList;
        }
        /// <summary>
        /// 将DataSet转换成TCenter_Main的List
        /// </summary>
        /// <param name="ds">传入的DataSet</param>
        /// <returns>TCenter_Main的List</returns>
        private List<Jy123.Model.TCenter_Main> DataSetToModelList(DataSet ds)
        {
            List<Jy123.Model.TCenter_Main> modelList = new List<Jy123.Model.TCenter_Main>();//转换成List
            int rowsCount = ds.Tables[0].Rows.Count;
            if (rowsCount > 0)
            {
                Jy123.Model.TCenter_Main model;
                for (int n = 0; n < rowsCount; n++)
                {
                    model = new Jy123.Model.TCenter_Main();
                    if (ds.Tables[0].Rows[n]["ID"].ToString() != "")
                    {
                        model.ID = int.Parse(ds.Tables[0].Rows[n]["ID"].ToString());
                    }
                    model.TName = ds.Tables[0].Rows[n]["TName"].ToString();
                    model.Logo = ds.Tables[0].Rows[n]["Logo"].ToString();
                    if (ds.Tables[0].Rows[n]["FUser"].ToString() != "")
                    {
                        model.FUser = int.Parse(ds.Tables[0].Rows[n]["FUser"].ToString());
                    }
                    if (ds.Tables[0].Rows[n]["FLevel"].ToString() != "")
                    {
                        model.FLevel = int.Parse(ds.Tables[0].Rows[n]["FLevel"].ToString());
                    }
                    if (ds.Tables[0].Rows[n]["FColor"].ToString() != "")
                    {
                        model.FColor = int.Parse(ds.Tables[0].Rows[n]["FColor"].ToString());
                    }
                    if (ds.Tables[0].Rows[n]["Capacity"].ToString() != "")
                    {
                        model.Capacity = int.Parse(ds.Tables[0].Rows[n]["Capacity"].ToString());
                    }
                    if (ds.Tables[0].Rows[n]["CurrentClubs"].ToString() != "")
                    {
                        model.CurrentClubs = int.Parse(ds.Tables[0].Rows[n]["CurrentClubs"].ToString());
                    }
                    if (ds.Tables[0].Rows[n]["Assets"].ToString() != "")
                    {
                        model.Assets = decimal.Parse(ds.Tables[0].Rows[n]["Assets"].ToString());
                    }
                    model.Description = ds.Tables[0].Rows[n]["Description"].ToString();
                    modelList.Add(model);
                }
            }
            return modelList;
        }

        /// <summary>
        /// 升级赛场，扣除相应费用
        /// </summary>
        /// <param name="TCenter">赛场</param>
        /// <param name="money">升级费用</param>
        /// <param name="user">用户</param>
        /// <returns>是否成功</returns>
        public bool UpgradeModule(Jy123.Model.TCenter_Main TCenter, decimal money, Jy123.Model.User_Main user)
        {
            try
            {
                Module_Main BLLModule = new Module_Main();
                TCenter_Main BLLTCenter = new TCenter_Main();
                User_Main BLLUser = new User_Main();
                Public_Level BLLLevel = new Public_Level();
                Model.Public_Level cLevel = BLLLevel.GetModel(TCenter.FLevel.Value);
                int nLNumber = cLevel.LevelNumber.Value + 1;
                string strWhere = string.Format("FJType = {0} AND LevelNumber = {1}", cLevel.FJType.Value, nLNumber.ToString());
                Model.Public_Level nLevel = BLLLevel.GetModelList(strWhere)[0];
                TCenter.FLevel = nLevel.ID;
                BLLTCenter.Update(TCenter);
                user.Cash = Convert.ToInt32(user.Cash.Value - money);
                BLLUser.Update(user);
                Model.Module_Main module = BLLModule.GetModel(TCenter.ID);
                BLL.Public.State state = new Jy123.BLL.Public.State();
                state.CreateModuleState(user, module, Convert.ToInt32(Public.EnumConfig.StateActionType.UpdateModule));
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void StartTrain(Model.TCenter_Main TCenter)
        {
            string strRaceClub = TCenter.TrainClub;
            string strForSQL = strRaceClub.Replace("_", ",");
            string[] str = strForSQL.Split(',');

            TCenter_Main BLLTCenter = new TCenter_Main();
            Club_Main BLLClub = new Club_Main();
            Module_Main BLLModule = new Module_Main();
            User_Main BLLUser = new User_Main();
            Public_Level BLLLevel = new Public_Level();
            Model.Public_Level level = BLLLevel.GetModel(TCenter.FLevel.Value);
            List<Model.Club_Main> listClub = BLLClub.GetModelList("ID IN (" + strForSQL + ")");
            Model.User_Main vUser = BLLUser.GetModel(TCenter.FUser.Value);
            List<Model.Module_Main> listModule = BLLModule.GetModelList("ID IN (" + strForSQL + ")");
            List<Model.User_Main> listFriend = BLLUser.GetModelList("ID IN (SELECT FUser FROM Club_Main WHERE ID IN (" + strForSQL + "))");
            Model.Module_Main tModule = BLLModule.GetModel(TCenter.ID);
            //扣除参赛费用
            decimal cost = 0;
            if (level.Cost.HasValue)
            {
                cost = level.Cost.Value;
            }
            vUser.Cash = Convert.ToInt32(vUser.Cash.Value + cost * listFriend.Count);
            BLLUser.Update(vUser);
            foreach (Model.User_Main user in listFriend)
            {
                user.Cash = Convert.ToInt32(user.Cash.Value - cost);
                BLLUser.Update(user);
            }
            foreach (Model.Club_Main club in listClub)
            {
                club.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Training);

                BLLClub.Update(club);
            }
            foreach (Model.Module_Main module in listModule)
            {
                module.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Training);          //设置俱乐部为比赛状态            
                BLLModule.Update(module);
            }
            TCenter.TrainClub = strForSQL;
            TCenter.CurrentClubs = str.Length;
            if (TCenter.Capacity.Value == str.Length)
            {
                TCenter.TStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.TCenterStatus.Max);//赛场状态设置为比赛
            }
            else
            {
                TCenter.TStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.TCenterStatus.Training);//赛场状态设置为比赛
            }

            tModule.MStatus = TCenter.TStatus;
            BLLTCenter.Update(TCenter);
            BLLModule.Update(tModule);
            BLL.TCenter_ClubTC BLLTC = new TCenter_ClubTC();
            List<Model.TCenter_ClubTC> listTC = BLLTC.GetModelList(string.Format("FTCenter = {0} AND TrainingTime IS NULL", TCenter.ID.ToString()));
            foreach (Model.Club_Main tClub in listClub)
            {
                if (!IsInList(tClub.ID, listTC))
                {
                    Model.TCenter_ClubTC TC = new Jy123.Model.TCenter_ClubTC();
                    TC.FClub = tClub.ID;
                    TC.FTCenter = TCenter.ID;
                    TC.StartTime = DateTime.Now;
                    TC.ClubName = tClub.CName;
                    BLLTC.Add(TC);
                }
            }
        }

        public void JoinTCenter(Model.Club_Main club, Model.TCenter_Main TCenter)
        {
            BLL.TCenter_ClubTC BLLTC = new TCenter_ClubTC();
            Model.TCenter_ClubTC TC = new Jy123.Model.TCenter_ClubTC();
            TC.FClub = club.ID;
            TC.FTCenter = TCenter.ID;
            TC.StartTime = DateTime.Now;
            TC.ClubName = club.CName;
            BLLTC.Add(TC);

            TCenter_Main BLLTCenter = new TCenter_Main();
            Club_Main BLLClub = new Club_Main();
            Module_Main BLLModule = new Module_Main();
            User_Main BLLUser = new User_Main();
            Public_Level BLLLevel = new Public_Level();
            Model.Public_Level level = BLLLevel.GetModel(TCenter.FLevel.Value);
            Model.User_Main vUser = BLLUser.GetModel(TCenter.FUser.Value);
            Model.Module_Main module = BLLModule.GetModel(club.ID);
            Model.User_Main friend = BLLUser.GetModel(club.FUser.Value);
            Model.Module_Main tModule = BLLModule.GetModel(TCenter.ID);
            //扣除参赛费用
            decimal cost = 0;
            if (level.Cost.HasValue)
            {
                cost = level.Cost.Value;
            }
            vUser.Cash = Convert.ToInt32(vUser.Cash.Value + cost);
            BLLUser.Update(vUser);

            friend.Cash = Convert.ToInt32(friend.Cash.Value - cost);
            BLLUser.Update(friend);

            club.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Training);

            BLLClub.Update(club);

            module.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Training);          //设置俱乐部为比赛状态            
            BLLModule.Update(module);
            if (!string.IsNullOrEmpty(TCenter.TrainClub))
            {
                TCenter.TrainClub = TCenter.TrainClub + "," + club.ID.ToString();
            }
            else
            {
                TCenter.TrainClub = club.ID.ToString();
            }

            TCenter.CurrentClubs = TCenter.CurrentClubs.Value + 1;
            if (TCenter.Capacity.Value == TCenter.CurrentClubs.Value)
            {
                TCenter.TStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.TCenterStatus.Max);//赛场状态设置为比赛
            }
            else
            {
                TCenter.TStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.TCenterStatus.Training);//赛场状态设置为比赛
            }

            tModule.MStatus = TCenter.TStatus;
            BLLTCenter.Update(TCenter);
            BLLModule.Update(tModule);

        }

        public void QuitTCenter(Model.Club_Main club, Model.TCenter_Main TCenter)
        {
            BLL.TCenter_ClubTC BLLTC = new TCenter_ClubTC();
            List<Model.TCenter_ClubTC> listTC = BLLTC.GetModelList(string.Format("FTCenter = {0} AND FClub = {1} AND TrainingTime IS NULL", TCenter.ID.ToString(), club.ID.ToString()));
            if (listTC.Count > 0)
            {
                Model.TCenter_ClubTC TC = listTC[0];
                TC.TrainingTime = 1;
                BLLTC.Update(TC);
            }

            TCenter_Main BLLTCenter = new TCenter_Main();
            Club_Main BLLClub = new Club_Main();
            Module_Main BLLModule = new Module_Main();
            User_Main BLLUser = new User_Main();
            Public_Level BLLLevel = new Public_Level();
            Model.Public_Level level = BLLLevel.GetModel(TCenter.FLevel.Value);
            Model.Module_Main module = BLLModule.GetModel(club.ID);
            Model.Module_Main tModule = BLLModule.GetModel(TCenter.ID);
            if (level.Liveness.HasValue)
            {
                club.LiveNess = club.LiveNess.Value + level.Liveness.Value;
            }
            if (level.Moral.HasValue)
            {
                club.Morale = club.Morale.Value + level.Moral.Value;
            }
            if (level.Skill.HasValue)
            {
                club.Skill = club.Skill.Value + level.Skill.Value;
            }
            if (level.PhysicalFitness.HasValue)
            {
                club.PhysicalFitness = club.PhysicalFitness.Value + level.PhysicalFitness.Value;
            }
            club.CStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Empty);

            BLLClub.Update(club);

            module.MStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.ClubStatus.Empty);          //设置俱乐部为比赛状态            
            BLLModule.Update(module);

            TCenter.TrainClub = TCenter.TrainClub.Replace("," + club.ID.ToString(), "").Replace(club.ID.ToString() + ",", "").Replace(club.ID.ToString(), "");
            TCenter.CurrentClubs = TCenter.CurrentClubs.Value - 1;
            if (TCenter.CurrentClubs.Value > 0)
            {
                TCenter.TStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.TCenterStatus.Training);//赛场状态设置为训练
            }
            else
            {
                TCenter.TStatus = Convert.ToInt32(Jy123.BLL.Public.EnumConfig.TCenterStatus.Empty);//赛场状态设置为空闲
            }

            tModule.MStatus = TCenter.TStatus;
            BLLTCenter.Update(TCenter);
            BLLModule.Update(tModule);
            BLL.Public.State BLLState = new Jy123.BLL.Public.State();
            Model.User_Main cUser = BLLUser.GetModel(club.FUser.Value);
            Model.User_Main tUser = BLLUser.GetModel(TCenter.FUser.Value);

            BLLState.CreateTrainState(cUser.ID.ToString(), cUser.UserName, club.ID.ToString(), club.CName, tUser, TCenter);
        }

        private bool IsInList(int id, List<Model.TCenter_ClubTC> listTC)
        {
            foreach (Model.TCenter_ClubTC TC in listTC)
            {
                if (id == TC.FClub.Value)
                {
                    return true;
                }
            }
            return false;
        }
    }
}
